import React, { useState } from 'react';
import { useParams } from 'react-router-dom';
import GopherProps from '../objects/internal/GopherProps';
import OrderDetails from '../components/OrderDetails';
import StaffTable from '../components/StaffTable';
import './StaffFragment.css';
import { Button, Card, Popconfirm, Space, message } from 'antd';
import { useTranslation } from 'react-i18next';
import StaffEditDialog from '../components/StaffEditDialog';

export default function StaffFragment(props: GopherProps) {
	const { id } = useParams<{id?: string}>();
	const {t} = useTranslation();
	const [selected, setSelected] = useState(false);
	const [isDeleting, setDeleting] = useState(false);
	const [selectedKey, setSelectedKey] = useState<string | undefined>(undefined);
	const [isBusy, setBusy] = useState(false);

	const [editDialogVisible, setEditDialogVisible] = useState(false);

	const onSelection = (keys: React.Key[]) => {
		console.log(keys);
		setSelected(keys.length > 0);
		if (keys.length > 0) {
			setSelectedKey(keys[0].toString());
		} else {
			setSelectedKey(undefined);
		}
	};

	const confirmDeletion = () => {
		setBusy(true);
		props.gopher.deleteStaff(selectedKey || '').then(() => {
			setBusy(false);
			setDeleting(false);
			message.success(t('popup-success'));
		});
	};

	const cancelDeletion = () => {
		setDeleting(false);
	};

	let child;

	if (id) {
		// detail mode
		child = (
			<OrderDetails id={id} gopher={props.gopher} />
		);
	} else {
		// table mode
		child = (
			<>
				<div className={'staff-component-wrapper'}>
					<Card>
						<Space>
							<Button type={'primary'} onClick={() => { setSelectedKey(undefined); setEditDialogVisible(true); }}>{t('button-add-staff')}</Button>
							<Button disabled={!selected} onClick={() => {setEditDialogVisible(true);}}>{t('button-edit-staff')}</Button>
							<Popconfirm title={t('dialog-delete-confirm')} visible={isDeleting} okButtonProps={{loading: isBusy}} cancelButtonProps={{loading: isBusy}} onCancel={cancelDeletion} onConfirm={confirmDeletion}>
								<Button type={'primary'} danger disabled={!selected} loading={isBusy} onClick={() => setDeleting(true)}>{t('button-delete-staff')}</Button>
							</Popconfirm>
						</Space>
					</Card>
				</div>
				<div className={'staff-component-wrapper'}>
					<StaffTable gopher={props.gopher} onSelection={onSelection} />
				</div>
			</>
		);
	}

	return (
		<div className={'staff-wrapper'}>
			{child}
			<StaffEditDialog visible={editDialogVisible} setVisibility={setEditDialogVisible} gopher={props.gopher} id={selectedKey} onOperationDone={() => { message.success(t('popup-success')) }} />
		</div>
	);
}
